<script>
import {ElMessage} from 'element-plus'
import ChineseDistricts from "@/assets/area";
import { ref } from "vue";
import img1 from "/src/assets/avatar.jpg";
import icon from "/src/assets/icon.png";
import axios from "axios";
export default {
  mounted(){
    const userData = JSON.parse(sessionStorage.getItem('token'));
    this.token = userData.token;
    this.userID = userData.userID;
    axios.defaults.headers.common['Authorization'] = `${this.token}`;

    // 获取头像
    const response = axios.get('http://localhost:8080/users/'+this.userID);
    response.then((result) => {
      // 这里的result就是Promise被解决后的返回值，也就是[[PromiseResult]]对应的值
      this.avatar = result.data.ProfilePhoto;
    }).catch((error) => {
      console.log(error);
    });

    //获取个人信息
    const response_1 = axios.get('http://localhost:8080/users/'+this.userID);
    response_1.then((result) =>{
      this.getContactInf = result.data.Contact;
      this.getContactType = result.data.ContactType;
      if(this.getContactType === '0'){
        this.getContactType = '微信';
      }
      else if(this.getContactType === '1'){
        this.getContactType = 'QQ';
      }
      else if(this.getContactType === '2'){
        this.getContactType = '电话';
      }
    }).catch((error) => {
      console.log(error);
    });
  },
  data(){
    return {
      img1,icon,
      hasNewMessages: false,
      userID:ref(0),
      token:ref(''),
      avatar:ref(null),
      isFirstToggle:ref(true),
      isAdopt:ref(false),   //是否为领养贴
      //isVisible:ref(false), //是否显示红星
      title:ref(""),  //标题

      getContactInf:ref(""),
      getContactType:ref(""),
      contact_inf:ref(""),
      contact_type:ref(""),
      passage:ref(""),
      passage_type:ref(""),
      files:ref([]),

      //选择省市
      province:[],
      shi1:[],
      city:[],
      block:[],
      pname:"",
      cname:"",

      //图片预览
      dialogVisible:ref(false),
      dialogImageUrl:ref(''),
      dialogWidth: 'auto',  // 初始宽度
      dialogHeight: 'auto',  // 初始高度

      //提交结果
      res:ref(null)
    }
  },
  methods:{
    // 选省市
    getCityData(){
      ChineseDistricts.forEach((item) => { // 使用箭头函数
        this.province.push({
          "id": item.code,
          "value": item.name,
          "children": item.cityList
        });
      });
    },
    // 选省
    choseProvince(e) {
      let that = this;
      that.city = [];
      that.block = [];
      that.cname = "";
      for (let index2 in this.province) {
        if (e === that.province[index2].id) {
          that.shi1 = that.province[index2].children;
          that.pname = that.province[index2].value;

          that.shi1.forEach(function(citem) {
            that.city.push({
              "id": citem.code,
              "value": citem.name,
              "children": citem.areaList
            });
          });
        }
      }
    },
    choseCity(e){
      for(let index2 in this.city){
        if(e === this.city[index2].id){
          this.cname = this.city[index2].value
        }
      }
    },

    // 头像点击
    avaClick(){
      this.$router.push({path:'/UserPage',query:{id:this.userID}})
    },
    discoverClick(){
      this.$router.push({path:'/MainPage'})
    },
    adoptClick(){
      this.$router.push({path:'/AdoptPage'})
    },
    msgClick(){
      this.$router.push({path:'/Message/like'})
    },
    toggleColor(){
      if(this.isFirstToggle === true){
        this.isFirstToggle = false;
        this.contact_inf = this.getContactInf;
        this.contact_type = this.getContactType;
      }
      this.isAdopt = !this.isAdopt

    },

    Handleexcced () {
      ElMessage({
        message: '只能上传9张图片',
        type: 'error',
        style: 'font-size:25px;font-weight:bold;',
        center: true,
        offset: 55
      })
    },
    handlePreview (uploadFile) {
      this.dialogImageUrl = uploadFile.url
      this.dialogVisible = true
    },
    handleRemove () {
      console.log("remove")
    },
    onImageLoad (event) {
      const img = event.target;
      let ratio = img.naturalWidth/img.naturalHeight;
      this.dialogWidth = 500*ratio + 'px'; // 设置对话框宽度为图像的自然宽度
      this.dialogHeight = 500 + 'px'; // 设置对话框高度为图像的自然高度
    },

    //发布按钮
    async postHandle() {
        // 是领养贴
        if (this.isAdopt) {
            if (this.title === '') {
                ElMessage({
                    message: '请填写标题',
                    type: 'error',
                    style: 'font-size:25px;font-weight:bold;',
                    center: true,
                    offset: 55
                })
                this.res = false
            }
            if (this.pname === '') {
                ElMessage({
                    message: '请选择省份',
                    type: 'error',
                    style: 'font-size:25px;font-weight:bold;',
                    center: true,
                    offset: 55
                })
                this.res = false
            }
            if (this.cname === '') {
                ElMessage({
                    message: '请选择城市',
                    type: 'error',
                    style: 'font-size:25px;font-weight:bold;',
                    center: true,
                    offset: 55
                })
                this.res = false
            }
            if (this.contact_inf === '') {
                ElMessage({
                    message: '请填写联系方式',
                    type: 'error',
                    style: 'font-size:25px;font-weight:bold;',
                    center: true,
                    offset: 55
                })
                this.res = false
            }
            if (this.contact_type === '') {
                ElMessage({
                    message: '请选择联系方式类型',
                    type: 'error',
                    style: 'font-size:25px;font-weight:bold;',
                    center: true,
                    offset: 55
                })
                this.res = false
            }
            if (this.passage === '') {
                ElMessage({
                    message: '请填写正文',
                    type: 'error',
                    style: 'font-size:25px;font-weight:bold;',
                    center: true,
                    offset: 55
                })
                this.res = false
            }
            if (this.files.length === 0) {
                ElMessage({
                    message: '请上传至少一张图片',
                    type: 'error',
                    style: 'font-size:25px;font-weight:bold;',
                    center: true,
                    offset: 55
                })
                this.res = false
            }
            if (this.title !== '' && this.pname !== '' && this.cname !== '' && this.contact_inf !== '' && this.contact_type !== '' && this.passage !== '' && this.files.length !== 0) {
              // 验证联系方式格式是否正确
              if(this.contact_type === '微信'){
                const wxReg = /^[a-zA-Z][a-zA-Z\d_-]{5,19}$/
                if(!wxReg.test(this.contact_inf)){
                  ElMessage({
                    message: '请输入正确格式的微信号',
                    type: 'error',
                    style: 'font-size:25px;font-weight:bold;',
                    center: true,
                    offset: 55
                  })
                  return
                }
              }
              else if(this.contact_type === 'QQ'){
                const qqReg = /^[1-9][0-9]{4,14}$/
                if(!qqReg.test(this.contact_inf)){
                  ElMessage({
                    message: '请输入正确格式的QQ号',
                    type: 'error',
                    style: 'font-size:25px;font-weight:bold;',
                    center: true,
                    offset: 55
                  })
                  return
                }
              }
              else if(this.contact_type === '电话'){
                const telReg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
                if(!telReg.test(this.contact_inf)){
                  ElMessage({
                    message: '请输入正确格式的手机号码',
                    type: 'error',
                    style: 'font-size:25px;font-weight:bold;',
                    center: true,
                    offset: 55
                  })
                  return
                }
              }
              // 提交到后端
              const formData = new FormData();
              formData.append("AuthorID", this.userID);
              formData.append("PassageTitle", this.title);

              for (let i = 0; i < this.files.length; i++) {
                formData.append("PassagePic", this.files[i].raw);
              }

              let passageType = ref("0");
              if(this.isAdopt === true){
                passageType.value = "1";
              }
              formData.append("PassageType", passageType.value);
              formData.append("PassageContent", this.passage);
              formData.append("Contact", this.contact_inf);

              let contactType = ref(null);
              if(this.contact_type === "微信"){
                contactType = '0';
              }
              else if(this.contact_type === 'QQ'){
                contactType = '1';
              }
              else if(this.contact_type === '电话'){
                contactType = '2';
              }
              console.log(contactType)
              formData.append("ContactType", contactType);
              formData.append("Province", this.pname);
              formData.append("City", this.cname);
              try {
                const response = await axios.post('http://localhost:8080/passageMana/upload', formData);
                if (response.status === 200) {
                    this.title = ''
                    this.pname = ''
                    this.cname = ''
                    this.passage = ''
                    this.files = []
                    ElMessage({
                      message: '发布成功',
                      type: 'success',
                      style: 'font-size:25px;font-weight:bold;',
                      offset: 55
                    })
                    this.res = true
                } else {
                  ElMessage({
                    message: '发布失败',
                    type: 'error',
                    style: 'font-size:25px;font-weight:bold;',
                    center: true,
                    offset: 55
                  })
                }
              } catch (error) {
                ElMessage({
                  message: '发布失败',
                  type: 'error',
                  style: 'font-size:25px;font-weight:bold;',
                  center: true,
                  offset: 55
                })
              }
              setTimeout(()=>{
                //获取个人信息
                const response_1 = axios.get('http://localhost:8080/users/'+this.userID);
                response_1.then((result) =>{
                  this.getContactInf = result.data.Contact;
                  this.getContactType = result.data.ContactType;
                  if(this.getContactType === '0'){
                    this.getContactType = '微信';
                  }
                  else if(this.getContactType === '1'){
                    this.getContactType = 'QQ';
                  }
                  else if(this.getContactType === '2'){
                    this.getContactType = '电话';
                  }
                }).catch((error) => {
                  console.log(error);
                });
                this.contact_inf = this.getContactInf
                this.contact_type =this.getContactType
              },3000)

            }
        }
        // 非领养贴
        else {
            if (this.title === '') {
                ElMessage({
                    message: '请填写标题',
                    type: 'error',
                    style: 'font-size:25px;font-weight:bold;',
                    center: true,
                    offset: 55
                })
                this.res = false
            }
            if (this.passage === '') {
                ElMessage({
                    message: '请填写正文',
                    type: 'error',
                    style: 'font-size:25px;font-weight:bold;',
                    center: true,
                    offset: 55
                })
                this.res = false
            }
            if (this.files.length === 0) {
                ElMessage({
                    message: '请上传至少一张图片',
                    type: 'error',
                    style: 'font-size:25px;font-weight:bold;',
                    center: true,
                    offset: 55
                })
                this.res = false
            }

            if (this.title !== '' && this.passage !== '' && this.files.length !== 0) {
                const flag = ref(false);
                // 如果两个不同时为空
                if (!((this.pname === '' && this.cname === '') || (this.pname !== '' && this.cname !== ''))) {
                    this.pname = ''
                    this.cname = ''
                    ElMessage({
                        message: '请同时填写省市或不填',
                        type: 'error',
                        style: 'font-size:25px;font-weight:bold;',
                        center: true,
                        offset: 55
                    })
                    flag.value = true
                    this.res = false
                }
                if (!((this.contact_inf === '' && this.contact_type === '' || (this.contact_inf !== '' && this.contact_type !== '')))) {
                    this.contact_inf = ''
                    this.contact_type = ''
                    ElMessage({
                        message: '请同时填写联系方式和联系方式类型或不填',
                        type: 'error',
                        style: 'font-size:25px;font-weight:bold;',
                        center: true,
                        offset: 55
                    })
                    flag.value = true
                    this.res = false
                }
                if (flag.value === true) {
                    return
                }
                else {
                  // 验证联系方式
                  if(this.contact_inf !=='' && this.contact_type !== ''){
                    // 验证联系方式格式是否正确
                    if(this.contact_type === '微信'){
                      const wxReg = /^[a-zA-Z][a-zA-Z\d_-]{5,19}$/
                      if(!wxReg.test(this.contact_inf)){
                        ElMessage({
                          message: '请输入正确格式的微信号',
                          type: 'error',
                          style: 'font-size:25px;font-weight:bold;',
                          center: true,
                          offset: 55
                        })
                        return
                      }
                    }
                    else if(this.contact_type === 'QQ'){
                      const qqReg = /^[1-9][0-9]{4,14}$/
                      if(!qqReg.test(this.contact_inf)){
                        ElMessage({
                          message: '请输入正确格式的QQ号',
                          type: 'error',
                          style: 'font-size:25px;font-weight:bold;',
                          center: true,
                          offset: 55
                        })
                        return
                      }
                    }
                    else if(this.contact_type === '电话'){
                      const telReg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
                      if(!telReg.test(this.contact_inf)){
                        ElMessage({
                          message: '请输入正确格式的手机号码',
                          type: 'error',
                          style: 'font-size:25px;font-weight:bold;',
                          center: true,
                          offset: 55
                        })
                        return
                      }
                    }
                  }
                  // 提交到后端
                  const formData = new FormData();
                  formData.append("AuthorID", this.userID);
                  formData.append("PassageTitle", this.title);

                  for (let i = 0; i < this.files.length; i++) {
                    formData.append("PassagePic", this.files[i].raw);
                  }

                  let passageType = ref("0");
                  if(this.isAdopt === true){
                    passageType.value = "1";
                  }
                  formData.append("PassageType", passageType.value);
                  formData.append("PassageContent", this.passage);
                  formData.append("Contact", this.contact_inf);

                  let contactType = ref(null);
                  if(this.contact_type === '微信'){
                    contactType = '0';
                  }
                  else if(this.contact_type === 'QQ'){
                    contactType = '1';
                  }
                  else if(this.contact_type === '电话'){
                    contactType = '2';
                  }
                  formData.append("ContactType", contactType);
                  if(this.pname === ''){
                    formData.append("Province", '未知');
                  }
                  else{
                    formData.append("Province", this.pname);
                  }
                  formData.append("City", this.cname);
                  try {
                    const response = await axios.post('http://localhost:8080/passageMana/upload', formData);
                    if (response.status === 200) {
                      this.title = ''
                      this.pname = ''
                      this.cname = ''
                      this.contact_inf = ''
                      this.contact_type = ''
                      this.passage = ''
                      this.files = []
                      ElMessage({
                        message: '发布成功',
                        type: 'success',
                        style: 'font-size:25px;font-weight:bold;',
                        offset: 55
                      })
                      this.res = true
                    } else {
                      ElMessage({
                        message: '发布失败',
                        type: 'error',
                        style: 'font-size:25px;font-weight:bold;',
                        center: true,
                        offset: 55
                      })
                    }
                  } catch (error) {
                    ElMessage({
                      message: '发布失败',
                      type: 'error',
                      style: 'font-size:25px;font-weight:bold;',
                      center: true,
                      offset: 55
                    })
                  }
                }

            }
        }

    },
  },
  created(){
    this.getCityData()
  }
}
</script>
<template>
    <div class="layout" style="height:100vh;">
      <el-container>
        <!--图标 头像-->
        <el-header class="header" >
          <el-row
              justify="space-between"
              style="padding-top: 10px;padding-bottom: 10px">

            <!--图标icon-->
            <img :src="icon"
                 style="width:55px;height:55px;"
                 alt=""/>

            <!--头像-->
            <el-avatar
                :class="'avatar'"
                :src="this.avatar"
                :fit="'cover'"
                :shape="'circle'"
                :size="55"
                @click="avaClick"
            />
          </el-row>

        </el-header>

        <el-container>
          <el-aside>
            <el-menu
                active-text-color="#FFD466"
                default-active="4"
            >
              <el-menu-item class="aside" index="1" @click="discoverClick">
                <el-icon :size="25" style="margin-right:10px;"><House /></el-icon>
                <span>发现</span>
              </el-menu-item>
              <el-menu-item class="aside" index="2" @click="adoptClick">
                <el-icon :size="25" style="margin-right:10px;"><Star /></el-icon>
                <span>领养</span>
              </el-menu-item>
              <el-menu-item class="aside" index="3" @click="msgClick">
                <el-icon :size="25" style="margin-right:10px;"><Message /></el-icon>
                     <span>消息</span>
                
              </el-menu-item>
              <el-menu-item class="aside" index="4" @click="sendClick">
                <el-icon :size="25" style="margin-right:10px;"><CirclePlus /></el-icon>
                <span>发布</span>
              </el-menu-item>
            </el-menu>
          </el-aside>

          <el-main>
            <div style="display: flex;flex-direction: column;align-items: stretch;gap: 10px;margin-left: 200px;margin-top:65px;">
              <el-row justify="start" style="margin-bottom: 10px;">
                  <span style="color:red;margin-top:4px;margin-right:5px;">*</span>

                  <el-input
                      class="titleInput"
                      v-model="this.title"
                      style="width: 250px;height:40px;font-size:16px;--el-input-inner-height: 16px;margin-right:15px;"
                      maxlength="15"
                      placeholder="请输入标题"
                      show-word-limit
                      type="text"
                  />

                <el-button class="toggleBtn"
                           :style="{backgroundColor:isAdopt ? '#FFD466':'#A6A6A6'}"
                           @click="toggleColor"
                            style="height:40px;font-size:16px;font-weight:bold;color:white;border:0;">
                  领养贴
                </el-button>

              </el-row>
              <el-row style="margin-bottom: 5px;">
                <span :style="{color:isAdopt ? 'red' : 'white'}"
                      style="margin-right:5px;margin-top:9px;">*</span>

                <el-select v-model="pname" @change="choseProvince" placeholder="请选择省份" style="width:170px;margin-right: 15px;" size="large">
                  <el-option
                      class="select_item"
                      v-for="(item,$index) in province"
                      :key="$index"
                      :label="item.value"
                      :value="item.id"
                  ></el-option>
                </el-select>

                <el-select v-model="cname" @change="choseCity" placeholder="请选择城市" style="width:170px;" size="large">
                  <el-option
                      class="select_item"
                      v-for="(item,$index) in city"
                      :key="$index"
                      :label="item.value"
                      :value="item.id">
                  </el-option>
                </el-select>

              </el-row>

              <el-row v-if="isAdopt">
                <span :style="{color:isAdopt ? 'red' : 'white'}"
                      style="margin-right:5px;margin-top:9px;">*</span>

                <el-input
                    v-model="contact_inf"
                    style="width: 250px;height:40px;font-size:16px;--el-input-inner-height: 16px;margin-right: 15px;margin-top:5px;"
                    maxlength="20"
                    placeholder="请输入联系方式"
                    type="text"
                />
                <el-radio-group v-model="contact_type" style="height:40px;margin-top:3px;">
                  <el-radio label="微信" value="微信" />
                  <el-radio label="QQ" value="QQ" />
                  <el-radio label="电话" value="电话" />
                </el-radio-group>

              </el-row>
              <el-row v-if="isAdopt">
                <span style="color:#A8ABB2;font-size:13px;margin-left:13px;">请注意：联系方式的修改会同步到个人信息</span>
              </el-row>

              <el-row>
                <span style="color:red;margin-right:5px;margin-top:2px;">*</span>
                <el-input
                    class="passageInput"
                    v-model="passage"
                    style="width: 618px;font-size:16px;--el-input-inner-height: 16px;"
                    resize="none"
                    maxlength="150"
                    :rows="6"
                    type="textarea"
                    placeholder="请输入正文"
                    show-word-limit
                />
              </el-row>

              <el-row>
                <span style="color:red;margin-right:5px;">*</span>
                <div class="el-uploadDiv">
                  <el-upload ref="uploadRef"
                             :auto-upload="false"
                             multiple :limit="9"
                             list-type="picture-card"
                             v-model:file-list="this.files"
                             :on-exceed="Handleexcced"
                             :on-remove="handleRemove"
                             :on-preview="handlePreview"
                             :show-file-list="true"
                             accept="image/png,image/jpeg,image/jpg"
                  >
                    <span style="font-size:60px;font-weight: lighter;">+</span>
                  </el-upload>
                  <el-dialog v-model="dialogVisible" :width="dialogWidth" :height="dialogHeight">
                    <el-image @load="onImageLoad" :fit="'cover'" :src="dialogImageUrl" alt="Preview Image" />
                  </el-dialog>
                </div>
              </el-row>


              <el-row justify="end" style="width:630px;">
                <el-button  class="sendBtn"
                            :="res"
                            @click="postHandle"
                            color="#FFD466"
                            style="font-size: 16px;font-weight:bold;color:white;height:40px;width:100px;">
                  发 布</el-button>
              </el-row>
            </div>
          </el-main>


        </el-container>


      </el-container>
    </div>
</template>


<style scoped>
::v-deep(.el-input._count){
  font-size:10px;
}
.el-avatar{
  cursor: pointer;
}
.el-menu{
  border:0!important;
}

/*header样式*/
.header{
  height:60px;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 1000;
}

/*aside*/
.el-aside{
  margin-left: 10px;
  width:180px;
  height:calc(100vh - 70px);
  padding-top:199px;
}

.aside{
  height:65px;
  font-size:18px;
  font-weight:bold;
  display: flex;
  justify-content: center;
  align-items: center;
}
::v-deep(.aside:hover){
  background-color: #FFE9B2;
}
/*领养贴按钮样式*/
.toggleBtn:hover{
  border:0;
}
/*省市选择样式*/
.select_item{
  height: 40px;
  line-height: 40px;
  font-size: 16px;
  width:170px;
}

::v-deep(.el-select__selection){
  font-size: 16px;

}
/*单选框样式*/
.el-radio ::v-deep(.el-radio__label) {
  font-size: 16px;
}
.el-radio ::v-deep(.el-radio__inner) {
  width: 16px;
  height: 16px;
  vertical-align: middle;
}

/*上传图片样式*/
.el-uploadDiv{
  width:650px;
  ::v-deep .el-upload--picture-card {
    width: 150px;
    position: relative;
    margin-right: 20px;
    /* 身份证样式*/
    ::v-deep .el-upload-list--picture-card .el-upload-list__item {
      width: 240px;
    }
  }
}

/*警示框样式*/
.el-message.error{
  --el-messagebox-font-size: 16px;
  font-size: 16px;
}
</style>


